package creator.single;

/**
 * 懒汉式:
 * 1. LazySingle  双重检测机制:  既保证效率, 又保证了线程安全性
 * 2. LazySingle2 静态内部类
 * 3. LazySingle3 枚举实现.
 * 静态实现方式: 都是在类装载时实现的, 是线程安全的
 */
public class LazySingle {

    private LazySingle() {

    }

    private static LazySingle instance;

    public final static LazySingle getInstance() {
        if (instance == null) {
            synchronized (LazySingle.class) {
                if (instance == null) {
                    instance = new LazySingle();
                }
            }
        }
        return instance;
    }
}

class LazySingle2 {
    private LazySingle2() {

    }

    public static class LazySingle2InsideClass {
        private final static LazySingle2 instance = new LazySingle2();
    }

    public static LazySingle2 getInstance() {
        return LazySingle2InsideClass.instance;
    }
}

enum LazySingle3 {
    SINGLE;

    public String say() {
        return "hh-VAVA";
    }
}

class Test2 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                LazySingle3 single1 = LazySingle3.SINGLE;
                LazySingle3 single2 = LazySingle3.SINGLE;
                System.out.println(single2 == single1);

                LazySingle2 single21 = LazySingle2.getInstance();
                LazySingle2 single22 = LazySingle2.getInstance();
                System.out.println(single21 == single22);


                LazySingle instance = LazySingle.getInstance();
                LazySingle instanc2 = LazySingle.getInstance();
                System.out.println(instanc2 == instance);
            }).start();
        }
    }
}










